package io.renren.modules.oss.controller;

import com.google.gson.Gson;
import io.renren.common.config.EbpConfig;
import io.renren.common.exception.RRException;
import io.renren.common.utils.*;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AliyunGroup;
import io.renren.common.validator.group.QcloudGroup;
import io.renren.common.validator.group.QiniuGroup;
import io.renren.modules.oss.cloud.CloudStorageConfig;
import io.renren.modules.oss.cloud.OSSFactory;
import io.renren.modules.oss.entity.SysOssEntity;
import io.renren.modules.oss.service.SysOssService;
import io.renren.modules.sys.service.SysConfigService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.omg.CORBA.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-25 12:13:26
 */
@RestController
@RequestMapping("sys/upload")
public class UploadController {
	@Autowired
	private SysOssService sysOssService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private EbpConfig ebpConfig;

    private final static String KEY = ConfigConstant.CLOUD_STORAGE_CONFIG_KEY;
	
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:oss:all")
	public R list(@RequestParam Map<String, Object> params){
		PageUtils page = sysOssService.queryPage(params);

		return R.ok().put("page", page);
	}


    /**
     * 云存储配置信息
     */
    @RequestMapping("/config")
    @RequiresPermissions("sys:oss:all")
    public R config(){
        CloudStorageConfig config = sysConfigService.getConfigObject(KEY, CloudStorageConfig.class);

        return R.ok().put("config", config);
    }


	/**
	 * 保存云存储配置信息
	 */
	@RequestMapping("/saveConfig")
	@RequiresPermissions("sys:oss:all")
	public R saveConfig(@RequestBody CloudStorageConfig config){
		//校验类型
		ValidatorUtils.validateEntity(config);

		if(config.getType() == Constant.CloudService.QINIU.getValue()){
			//校验七牛数据
			ValidatorUtils.validateEntity(config, QiniuGroup.class);
		}else if(config.getType() == Constant.CloudService.ALIYUN.getValue()){
			//校验阿里云数据
			ValidatorUtils.validateEntity(config, AliyunGroup.class);
		}else if(config.getType() == Constant.CloudService.QCLOUD.getValue()){
			//校验腾讯云数据
			ValidatorUtils.validateEntity(config, QcloudGroup.class);
		}

        sysConfigService.updateValueByKey(KEY, new Gson().toJson(config));

		return R.ok();
	}
	

	/**
	 * 上传文件
	 */
	@RequestMapping("/upload")
	public R upload(@RequestParam("file") MultipartFile file,@Value("${ebpConfig.ftpUrl}") String redisOpen) throws Exception {
		System.err.println("dsfsdfsdfsd:"+redisOpen);
		if (file.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}
        String ftpUrl = ebpConfig.getFtpUrl();
        int ftpPoint = ebpConfig.getFtpPoint();
        String ftpPath = ebpConfig.getFtpPath();
        String ftpUserName = ebpConfig.getFtpUserName();
        String ftpPassword = ebpConfig.getFtpPassword();
        String fileServerUrl = ebpConfig.getFileServerUrl();
        String fileDatePath = EBPUtils.getDateStr2();

        //String path = request.getSession().getServletContext().getRealPath("upload/")+EBPUtils.getDateStr();
		//path = "/Users/liupengfei/Downloads/ftp/"+EBPUtils.getDateStr();
		//System.err.println("路径："+path);
		//上传文件
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		System.err.println("上传文件:"+suffix);
        String fileName = file.getOriginalFilename();
        System.err.println("文件名称:"+fileName);
        String url = "";
		//String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);
        // 如果名称不为“”,说明该文件存在，否则说明该文件不存在
        if (fileName.trim() != "") {
            String fileNewName = UUID.randomUUID().toString().replace("-", "")+suffix;
            System.err.println("新文件名称:"+fileNewName);
            //服务器文件存储
//            File targetFile = new File(path);
//            if (!targetFile.exists()) {
//            targetFile.mkdirs();

            boolean result = FtpUtil.uploadFile(ftpUrl,ftpPoint,ftpUserName,
                    ftpPassword,ftpPath,fileDatePath,fileNewName, file.getInputStream());
            System.out.println("上传状态:"+result);
            url = fileServerUrl+"/"+fileDatePath+"/"+fileNewName;
            System.out.println("文件连接："+url);
            //文件保存到当前服务器
            //File targetFile2 = new File(path,fileNewName);
            //file.transferTo(targetFile2);
        }

		//保存文件信息
		SysOssEntity ossEntity = new SysOssEntity();
		ossEntity.setUrl(url);
		ossEntity.setCreateDate(new Date());
		sysOssService.insert(ossEntity);

		return R.ok().put("url", url);
	}


	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("sys:oss:all")
	public R delete(@RequestBody Long[] ids){
		sysOssService.deleteBatchIds(Arrays.asList(ids));

		return R.ok();
	}

}
